package gin

import (
	"log"
	"managementsystem/structs"
	"managementsystem/test"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
)

func isSnoExists(db *gorm.DB, data string) bool {
	var s structs.S

	err := db.Table("s").Where("sno = ?", data).First(&s).Error

	if err == nil {
		return true
	}

	if data == s.Sno {
		return true
	}
	return false
}

func Start(db *gorm.DB) {
	var data structs.S

	r := gin.Default()
	r.POST("/search/infosearch", func(ctx *gin.Context) {
		//获取参数
		data.Sno = ctx.PostForm("sno")
		//数据验证
		if len(data.Sno) != 6 {
			ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "学号必须6位"})
			return
		}
		//查询学号是否存在
		if !isSnoExists(db, data.Sno) {
			ctx.JSON(200, gin.H{
				"msg": "学号不存在, 查询失败",
			})
			return
		}

		//返回结果
		data = test.Select_one_info_view(db, data)

		ctx.JSON(200, gin.H{
			"msg": "查询成功" + data.Sno + data.Sname + data.Smajor,
		})
		log.Println(data)
	})
	r.Run() // 监听并在 0.0.0.0:8080 上启动服务
}
